package com.example.portablefortheelderlybackground.utils;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import org.springframework.data.redis.core.StringRedisTemplate;

import java.util.Collection;
import java.util.concurrent.TimeUnit;

public class RedisCache {
    private final static StringRedisTemplate stringRedisTemplate = new StringRedisTemplate();

    /**
     * @param key  redis的key值
     * @param type key的所属类的类型
     * @return T
     * @description: 根据key获取对应的缓 值存
     * @author 86187
     * @date: 2023/7/19 9:53
     */

    public static <T> T get(final String key, Class<T> type) {
        final String json = stringRedisTemplate.opsForValue().get(key);
        if (StringUtils.isBlank(json)) {
            return null;
        }
        return JSONUtil.toBean(json, type);
    }

    public static <T> void set(final String key, final T value) {
        //默认过期时间为30分钟
        set(key, value, 30, TimeUnit.MINUTES);
    }

    public static <T> void set(final String key, final T value, final long time, final TimeUnit expire) {
        String jsonStr = JSONUtil.toJsonStr(value);
        //缓存
        stringRedisTemplate.opsForValue().set(key, jsonStr, time, expire);
    }

    //设置key的过期时间
    public static Boolean expire(final String key, final long time, final TimeUnit expire) {
        return stringRedisTemplate.expire(key, time, expire);
    }

    public static Boolean delete(final String key) {
        // 删除key
        return stringRedisTemplate.delete(key);
    }

    public static void deleteBatch(Collection<String> collection) {
        stringRedisTemplate.delete(collection);
    }
}
